<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>商品管理 - 智慧小区管理系统</title>
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css">
    <style>
        body {
            padding: 16px;
            background: #f5f7fa;
            height: 100vh;
            overflow: hidden;
        }
        .product-toolbar {
            margin-bottom: 12px;
            padding: 12px;
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .layui-table th, .layui-table td {
            text-align: center;
            padding: 8px 12px;
        }
        .layui-table thead tr {
            background-color: #f8f9fa;
        }
        .product-image {
            width: 50px;
            height: 50px;
            object-fit: cover;
            border-radius: 4px;
            border: 1px solid #e6e6e6;
            cursor: pointer;
            transition: transform 0.2s;
        }
        .product-image:hover {
            transform: scale(1.1);
        }
        .layui-form-label {
            width: 100px;
        }
        .layui-input-block {
            margin-left: 130px;
        }
        .layui-word-aux {
            color: #999;
            font-size: 12px;
            margin-top: 5px;
         }
        .layui-table-cell{
            height:auto;
            line-height: 30px;
        }
    </style>
</head>
<body>
<div class="layui-card">
    <div class="layui-card-header" style="font-size:1.2em;font-weight:bold;">商品管理</div>
    <div class="layui-card-body">
        <!-- 搜索表单 -->
        <form class="layui-form product-toolbar" id="searchForm">

            <div class="layui-inline">
                <input type="text" name="name" placeholder="商品名称" class="layui-input" style="width: 150px;">
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 60px;">分类</label>
                <div class="layui-input-inline" style="width: 120px;">
                    <select name="category" id="categorySelect">
                        <option value="">请选择分类</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 60px;">库存</label>
                <div class="layui-input-inline" style="width: 100px;">
                    <select name="stockFilter">
                        <option value="">全部</option>
                        <option value="inStock">有库存</option>
                        <option value="lowStock">库存不足</option>
                        <option value="outOfStock">无库存</option>
                    </select>
                </div>
            </div>
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="search"><i class="layui-icon layui-icon-search"></i> 查询</button>
            <button class="layui-btn layui-btn-primary" type="reset"><i class="layui-icon layui-icon-refresh"></i> 重置</button>

            <!-- 统计信息 -->
            <div style="display: inline-flex; gap: 8px; margin-left: 20px;">
                <div class="layui-card" style="margin-bottom: 0; min-width: 80px;">
                    <div class="layui-card-body" style="text-align: center; padding: 5px;">
                        <div style="font-size: 20px; color: #1E9FFF; font-weight: bold;" id="totalProducts">0</div>
                        <div style="color: #666; font-size: 16px;">总数</div>
                    </div>
                </div>
                <div class="layui-card" style="margin-bottom: 0; min-width: 80px;">
                    <div class="layui-card-body" style="text-align: center; padding: 5px;">
                        <div style="font-size: 20px; color: #5FB878; font-weight: bold;" id="inStockProducts">0</div>
                        <div style="color: #666; font-size: 16px;">有库存</div>
                    </div>
                </div>
                <div class="layui-card" style="margin-bottom: 0; min-width: 80px;">
                    <div class="layui-card-body" style="text-align: center; padding: 5px;">
                        <div style="font-size: 20px; color: #FFB800; font-weight: bold;" id="lowStockProducts">0</div>
                        <div style="color: #666; font-size: 16px;">库存不足</div>
                    </div>
                </div>
                <div class="layui-card" style="margin-bottom: 0; min-width: 80px;">
                    <div class="layui-card-body" style="text-align: center; padding: 5px;">
                        <div style="font-size: 20px; color: #FF5722; font-weight: bold;" id="outOfStockProducts">0</div>
                        <div style="color: #666; font-size: 16px;">无库存</div>
                    </div>
                </div>
            </div>
        </form>

        <!-- 工具栏 -->
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>
                <button class="layui-btn layui-btn-primary layui-btn-sm" onclick="refreshTable()"> 刷新 </button>
            </div>
        </script>


        <!-- 数据表格 -->
        <div style="background: #fff; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
            <table class="layui-table" id="productTable" lay-filter="productTableFilter"></table>
        </div>

        <!-- 操作栏模板 -->
        <script type="text/html" id="tableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs"
               lay-event="edit">
                <i class="layui-icon layui-icon-edit"></i> 编辑
            </a>
            <a class="layui-btn layui-btn-danger layui-btn-xs"
               lay-event="delete">
                <i class="layui-icon layui-icon-delete"></i> 删除
            </a>
        </script>

        <!-- 商品图片列模板 -->
        <script type="text/html" id="imageTpl">
            {{# if(d.imageUrl) { }}
            <img src="{{d.imageUrl}}" class="product-image" onerror="this.src='../images/default_picture.png'">
            {{# } else { }}
            <img src="../images/default_picture.png" class="product-image">
            {{# } }}
        </script>

        <!-- 添加/编辑模态框 -->
        <div id="edit" style="display: none; padding: 10px;">
            <form class="layui-form" id="formData" lay-filter="editForm">
                <div class="layui-form-item" id="product-laylabel">
                    <label class="layui-form-label">商品ID</label>
                    <div class="layui-input-block">
                        <input type="number" name="productId" placeholder="系统自动生成" class="layui-input" readonly>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">商品名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" placeholder="请输入商品名称" class="layui-input" maxlength="100" lay-verify="required">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">商品分类</label>
                    <div class="layui-input-block">
                        <select name="category" id="editCategorySelect" lay-verify="required" lay-filter="category">
                            <option value="">请选择分类</option>
                        </select>
                        <input type="text" id="customCategoryInput" name="customCategory" placeholder="请输入自定义分类" class="layui-input" style="display:none;margin-top:8px;max-width:220px;">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">单价(元)</label>
                    <div class="layui-input-block">
                        <input type="number" name="price" placeholder="请输入单价" class="layui-input" step="0.01" min="0" lay-verify="required|number">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">库存数量</label>
                    <div class="layui-input-block">
                        <input type="number" name="stock" placeholder="请输入库存数量" class="layui-input" min="0" lay-verify="required|number">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">商品单位</label>
                    <div class="layui-input-block">
                        <input type="text" name="units" placeholder="如：斤、瓶、个" class="layui-input" maxlength="255" lay-verify="required">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">商品图片</label>
                    <div class="layui-input-block">
                        <input type="file" id="imageUpload" accept="image/*" style="margin-bottom:8px;">
                        <input type="hidden" name="imageUrl" id="imageUrl">
                        <img id="imagePreview" class="product-image" style="display:none;">
                        <div class="layui-form-mid layui-word-aux">请上传商品图片，支持jpg/png等格式</div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">商品描述</label>
                    <div class="layui-input-block">
                        <textarea name="description" placeholder="请输入商品描述" class="layui-textarea" rows="3"></textarea>
                        <div class="layui-form-mid layui-word-aux">可选字段，用于详细描述商品信息</div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="formSubmit">提交</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="../lib/layui-v2.6.3/layui.js"></script>
<script>
    layui.use(['table', 'form', 'layer', 'jquery'], function () {
        const table = layui.table;
        const form = layui.form;
        const layer = layui.layer;
        const $ = layui.jquery;
        // 全局设置ajax请求头
        $.ajaxSetup({
            beforeSend: function(xhr) {
                const data = JSON.parse(localStorage.getItem('user'));
                //输出token
                console.log(data.token);
                if (data.token) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + data.token);
                }
            }
        });

        let index;
        // 当前操作类型（add/edit）
        let currentAction = 'add';
        // 当前编辑的商品ID
        let currentEditId = null;

        // 全局变量存储所有商品数据
        let allProductData = [];
        let filteredProductData = [];
        // 新增：缓存分类
        let cachedCategories = [];

        // 初始化表格
        table.render({
            elem: '#productTable',
            data: [],
            toolbar: '#toolbarDemo',
            page: true,
            limit: 10,
            limits: [10, 15, 20, 50],
            height: 'full-200',
            done: function(res) {
                // 表格数据加载完成后的回调
            },
            cols: [[
                { field: 'productId', title: '商品ID', width: 120, sort: true, align: 'center' },
                { field: 'imageUrl', title: '商品图片', width: 120, templet: '#imageTpl', align: 'center' },
                { field: 'name', title: '商品名称', width: 180, align: 'center' },
                { field: 'category', title: '分类', width: 100, align: 'center', templet: function(d) {
                        return '<span class="layui-badge layui-bg-blue">' + (d.category || '-') + '</span>';
                    }},
                { field: 'price', title: '单价(元)', width: 120, align: 'center', templet: function(d) {
                        return '<span style="color: #e74c3c; font-weight: bold;">¥' + d.price + '</span>';
                    }},
                { field: 'stock', title: '库存', width: 100, align: 'center', templet: function(d) {
                        var stockClass = d.stock > 10 ? 'layui-bg-green' : d.stock > 0 ? 'layui-bg-orange' : 'layui-bg-red';
                        return '<span class="layui-badge ' + stockClass + '">' + d.stock + '</span>';
                    }},
                { field: 'units', title: '单位', width: 100, align: 'center' },
                { field: 'description', title: '描述', width: 250, align: 'center', templet: function(d) {
                        if (d.description && d.description.length > 18) {
                            return '<span title="' + d.description + '">' + d.description.substring(0, 18) + '...</span>';
                        }
                        return d.description || '-';
                    }},
                { title: '操作', toolbar: '#tableBar', width: 220, align: 'center', fixed: 'right' }
            ]]
        });

        // 监听工具栏事件
        table.on('toolbar(productTableFilter)', function(obj){
            if (obj.event === 'add') {
                currentEditId = null; // 设置为添加模式
                $("#product-laylabel").hide(); // 添加时隐藏商品ID字段

                // 先打开弹窗
                index = layer.open({
                    title: '添加商品',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['50%', '70%'],
                    content: $("#edit")
                });

                // 重新加载分类选项并清空表单
                loadCategoriesAndClearForm();

                $(window).on("resize", function () {
                    layer.full(index);
                });
            }
        });

        // 监听行工具事件
        table.on('tool(productTableFilter)', function(obj){
            const data = obj.data;
            if(obj.event === 'edit') {
                currentEditId = data.productId; // 设置为编辑模式，记录当前编辑的商品ID
                $("#product-laylabel").show();

                // 先打开弹窗
                index = layer.open({
                    title: '编辑商品信息',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['50%', '70%'],
                    content: $("#edit")
                });

                // 重新加载分类选项，加载完成后再设置表单值
                loadCategoriesAndSetForm(data);

                // 恢复商品ID字段的验证规则（在表单加载完成后）
                setTimeout(function() {
                    $('input[name="productId"]').attr('lay-verify', 'number');
                    form.render();
                }, 100);

                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if(obj.event === 'delete') {
                layer.confirm('确定删除该商品吗？', function(index){
                    // 连接后端删除接口
                    $.getJSON('/product/delete/'+data.productId, function(res){
                        if(res.code === 0) {
                            layer.msg('删除成功');
                            loadAllProducts(); // 重新加载所有数据
                        } else {
                            layer.msg('删除失败: ' + res.message);
                        }
                    });
                    layer.close(index);
                });
            }
        });

        // 监听分类下拉框选择，显示/隐藏自定义分类输入框
        form.on('select(category)', function(data) {
            if (data.value === '__custom__') {
                $('#customCategoryInput').show();
            } else {
                $('#customCategoryInput').hide();
            }
        });

        // 提交表单数据
        form.on('submit(formSubmit)', function(data){
            var field = data.field;

            // 数据验证
            if (!field.name || field.name.trim() === '') {
                layer.msg('请输入商品名称', {icon: 2});
                return false;
            }
            if (!field.category || field.category.trim() === '') {
                layer.msg('请选择商品分类', {icon: 2});
                return false;
            }
            if (!field.price || parseFloat(field.price) <= 0) {
                layer.msg('请输入有效的单价', {icon: 2});
                return false;
            }
            if (!field.stock || parseInt(field.stock) < 0) {
                layer.msg('请输入有效的库存数量', {icon: 2});
                return false;
            }
            if (!field.units || field.units.trim() === '') {
                layer.msg('请输入商品单位', {icon: 2});
                return false;
            }

            // 如果选择了自定义分类，使用自定义分类内容
            if (field.category === '__custom__') {
                if (!field.customCategory || field.customCategory.trim() === '') {
                    layer.msg('请输入自定义分类', {icon: 2});
                    return false;
                }
                field.category = field.customCategory.trim();
            }

            // 判断是否选择了图片文件
            var fileInput = document.getElementById('imageUpload');
            var file = fileInput && fileInput.files[0];

            function doSubmit(imageUrl) {
                field.imageUrl = imageUrl || $('#imageUrl').val();
                var url = currentEditId ? '/product/update' : '/product/add';
                var postData = field;
                if (currentEditId) {
                    postData.originalId = currentEditId;
                }
                $.post(url, postData, function(res){
                    if(res.code === 0) {
                        layer.msg(currentEditId ? "更新成功" : "添加成功", {icon: 1});
                        layer.close(index);
                        loadAllProducts();
                    } else {
                        layer.msg((currentEditId ? "更新失败" : "添加失败") + ": " + (res.message || ''), {icon: 2});
                    }
                }).fail(function() {
                    layer.msg('网络错误，请稍后重试', {icon: 2});
                });
            }

            if (file) {
                // 有图片，判断是上传还是更新
                var formData = new FormData();
                formData.append('file', file);
                
                // 如果是编辑模式且有旧图片，使用更新接口
                var uploadUrl = '/oss/upload';
                if (currentEditId && $('#imageUrl').val()) {
                    uploadUrl = '/oss/update';
                    formData.append('oldFileUrl', $('#imageUrl').val());
                }
                
                layer.msg('图片上传中...', {icon: 16, shade: 0.2, time: 0});
                $.ajax({
                    url: uploadUrl,
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        layer.closeAll('loading');
                        if (res.code === 0) {
                            doSubmit(res.data);
                        } else {
                            layer.msg('图片上传失败: ' + res.message, {icon: 2});
                        }
                    },
                    error: function() {
                        layer.closeAll('loading');
                        layer.msg('图片上传失败', {icon: 2});
                    }
                });
            } else {
                // 没有图片，直接提交
                doSubmit();
            }
            return false;
        });

        // 渲染分类下拉框（搜索和编辑）
        function renderCategorySelect() {
            cachedCategories = [...new Set(allProductData.map(item => item.category))].filter(Boolean);
            // 搜索表单
            var searchSelect = $('#categorySelect');
            searchSelect.find('option:not(:first)').remove();
            cachedCategories.forEach(function(cat) {
                searchSelect.append(`<option value="${cat}">${cat}</option>`);
            });
            // 编辑表单
            var editSelect = $('#editCategorySelect');
            editSelect.find('option:not(:first)').remove();
            cachedCategories.forEach(function(cat) {
                editSelect.append(`<option value="${cat}">${cat}</option>`);
            });
            editSelect.append('<option value="__custom__">自定义</option>');
            form.render('select');
        }

        // 加载所有商品数据
        function loadAllProducts() {
            $.get('/product/list', function(res) {
                if (res.code === 0 && res.data) {
                    allProductData = res.data;
                    filteredProductData = [...allProductData];
                    updateTableData();
                    updateStatistics();
                    renderCategorySelect(); // 新增：加载后渲染分类
                }
            });
        }

        // 更新表格数据
        function updateTableData() {
            table.reload('productTable', {
                data: filteredProductData
            });
        }

        // 前端筛选逻辑
        function filterProducts(searchParams) {
            filteredProductData = allProductData.filter(function(product) {
                // 商品名称筛选
                if (searchParams.name && !product.name.includes(searchParams.name)) {
                    return false;
                }
                // 分类筛选
                if (searchParams.category && product.category !== searchParams.category) {
                    return false;
                }
                // 库存筛选
                if (searchParams.stockFilter) {
                    switch (searchParams.stockFilter) {
                        case 'inStock':
                            if (product.stock <= 10) return false;
                            break;
                        case 'lowStock':
                            if (product.stock <= 0 || product.stock > 10) return false;
                            break;
                        case 'outOfStock':
                            if (product.stock !== 0) return false;
                            break;
                    }
                }
                return true;
            });
            updateTableData();
        }

        // 搜索提交
        form.on('submit(search)', function (data) {
            console.log('搜索参数:', data.field); // 调试信息
            filterProducts(data.field);
            return false;
        });

        // 重置按钮点击事件
        $(document).on('click', '.layui-btn-primary[type="reset"]', function () {
            $('#searchForm')[0].reset();
            form.render();
            filteredProductData = [...allProductData];
            updateTableData();
            return false;
        });

        // 图片选择时只本地预览，不上传
        $('body').on('change', '#imageUpload', function() {
            var file = this.files[0];
            if (!file) return;
            var reader = new FileReader();
            reader.onload = function(e) {
                $('#imagePreview').attr('src', e.target.result).show();
            };
            reader.readAsDataURL(file);
            // 不上传
        });

        // 表格中图片点击预览
        $(document).on('click', '.product-image', function() {
            var src = $(this).attr('src');
            if (src && src !== '../images/default_picture.png') {
                layer.photos({
                    photos: {
                        "title": "商品图片预览",
                        "data": [{
                            "src": src
                        }]
                    }
                });
            }
        });

        // 添加/编辑弹窗打开时，重置自定义分类输入框
        function loadCategoriesAndSetForm(data) {
            renderCategorySelect();
            form.val("editForm", data);
            form.render();
            $('#customCategoryInput').hide();
            if (data.imageUrl) {
                $('#imagePreview').attr('src', data.imageUrl).show();
            } else {
                $('#imagePreview').hide();
            }
        }
        function loadCategoriesAndClearForm() {
            renderCategorySelect();
            form.val("editForm", {
                name: '',
                category: '',
                price: '',
                stock: '',
                units: '',
                imageUrl: '',
                description: ''
            });
            form.render();
            $('#customCategoryInput').hide();
            $('#imagePreview').hide();
        }

        // 更新统计信息
        function updateStatistics() {
            $.get('/product/list', function(res) {
                if (res.code === 0 && res.data) {
                    var products = res.data;
                    var total = products.length;
                    var inStock = products.filter(p => p.stock > 10).length;
                    var lowStock = products.filter(p => p.stock > 0 && p.stock <= 10).length;
                    var outOfStock = products.filter(p => p.stock === 0).length;

                    $('#totalProducts').text(total);
                    $('#inStockProducts').text(inStock);
                    $('#lowStockProducts').text(lowStock);
                    $('#outOfStockProducts').text(outOfStock);
                }
            });
        }

        // 刷新表格
        function refreshTable() {
            loadAllProducts();
            layer.msg('数据已刷新', {icon: 1});
        }

        // 页面初始化时加载所有商品数据（分类下拉框随商品数据自动渲染）
        $(function() {
            loadAllProducts();
        });
    });
</script>
</body>
</html> 